package chattle.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.jdo.PersistenceManager;

import chattle.client.UserMgmtService;
import chattle.shared.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
public class UserMgmtServiceImpl extends RemoteServiceServlet implements UserMgmtService {

	private static final long serialVersionUID = -403262222284527584L;
	
	@Override
	public User getUser() {
		PersistenceManager pm = PMFSingleton.getPM();
		User user = UserManager.getCurrentUser(pm);
		System.out.println(user);
		pm.close();
		return user;
	}

	@Override
	public String getLoginURL(String openIdUrl, String backUrl) {
		return UserManager.getLoginURL(openIdUrl, backUrl);
	}

	@Override
	public String getLogoutURL(String backUrl) {
		return UserManager.getLogoutURL(backUrl);
	}
	
	public boolean logout()
	{
		try {
			URL logoutURL = new URL(getLogoutURL("/"));
			InputStream conn = logoutURL.openStream();
			conn.close();
			User user = getUser();
			if(user == null)
				return true;
			else
				return false;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
